<template>
  <el-dialog title="添加分类" :visible.sync="dialogFormVisible">
    <el-form :model="form">
      <el-form-item label="pid" label-width="120">
        <el-input v-model="form.id" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="name" label-width="120">
        <el-input v-model="form.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="lev" label-width="120">
        <el-cascader
          :label-width="120+''"
          :options="options"
          :props="{ expandTrigger: 'hover' }"
          @change="handleChange"></el-cascader>
      </el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="dialogFormVisible = false;submit()">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import { addCategories, getCategories } from '@/api/categories'
import { MessageType } from 'element-ui/types/message'

interface Data {
  'cat_id':number,
  'cat_name':string,
  children?:Array<Data>
}
interface Option {
  value:number,
  label:string,
  children?:Array<Option>
}
@Component
export default class CategoriesAdd extends Vue {
  private dialogFormVisible = false
  private form={ pid: 0, name: '', level: 0 }
  private render1?:()=>void
  private options:Array<Option>=[]

  isOpen (render?:()=>void) {
    this.dialogFormVisible = !this.dialogFormVisible
    this.render1 = render
  }

  // 链表查询start
  dataToOptions (dataList:Array<Data>) {
    return dataList.map(data => {
      const option:Option = {
        label: data.cat_name,
        value: data.cat_id
      }
      if (data.children) {
        option.children = this.dataToOptions(data.children)
      }
      return option
    })
  }

  async getList () {
    const { data } = await getCategories({})
    this.options = this.dataToOptions(data)
  }

  mounted () {
    this.getList()
  }

  handleChange (num:Array<number>) {
    this.form.level = num[num.length - 1]
  }
  // 链表end

  async submit () {
    const { data, meta } = await addCategories(this.form)
    let type:MessageType
    if (meta.status >= 200 && meta.status < 300) {
      type = 'success'
    } else {
      type = 'error'
    }
    this.$message({
      message: meta.msg,
      type
    })
  }
}
</script>

<style scoped>

</style>
